package iot.servlet;

import iot.bean.Tuser;
import iot.dao.UserDao;
import iot.utils.CodeExchange;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class UserServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UserServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@SuppressWarnings("static-access")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 当进行用户登录、用户信息删除、用户信息添加和用户信息修改时，数据递交给 S，并传递 action 参数，下文根据 action
		// 参数执行对应操作
		String action = request.getParameter("action");
		if (action != null) {
			if (action.equals("delete")) {
				String id = request.getParameter("id");
				if (id != null && id.length() > 0) {
					UserDao userDao = new UserDao();
					if (userDao.delete(id)) {
						request.setAttribute("msg", "删除成功！");
					} else {
						request.setAttribute("msg", "删除失败！");
					}
				} else {
					response.sendRedirect("error.jsp");// 设计一个错误页面来显示
					return;
				}
			} else if (action.equals("add")) {
				Tuser user = new Tuser();
				// 获取数据，存放到值 JavaBean user
				user.setUsername(CodeExchange.chinese(request.getParameter("username")));
				user.setPassword(CodeExchange.chinese(request.getParameter("password")));
				user.setUsertype(CodeExchange.chinese(request.getParameter("usertype")));
				// 定义 UserDao（用户信息处理的 JavaBean），调用 add()方法实现用户信息添加
				UserDao userDao = new UserDao();
				// 这里还可以进一步查询用户名是否存在，避免用户名重复
				if (userDao.add(user)) {
					request.setAttribute("msg", "添加成功！");
				} else {
					request.setAttribute("msg", "添加失败！");
				}
				// 用户信息更新操作
			} else if (action.equals("update")) {
				// 注意在 useredit.jsp 文件中，查看表单，可发现 id 作为隐藏信息进行传递。
				String id = request.getParameter("id");
				if (id != null && id.length() > 0) {
					UserDao userDao = new UserDao();
					// 根据 id 值进行数据查询，结果存放在 users 集合中
					ArrayList<Tuser> users = userDao.query(" id=" + id);
					if (users != null && users.size() > 0) {
						Tuser user = users.get(0);// 获取用户信息，存放在值 JavaBean 中
						request.setAttribute("user", user);// 要更新的数据记录存放在
															// request 对象中
						// 转向修改页面编辑信息，注意此位置有 return 语句，请思考其意义
						request.getRequestDispatcher("useredit.jsp").forward(
								request, response);
						return;
					} else {
						response.sendRedirect("error.jsp");// 设计一个错误页面来显示
						return;
					}
				} else {
					response.sendRedirect("error.jsp");// 设计一个错误页面来显示
					return;
				}
			} else if (action.equals("updateSave")) {
				Tuser user = new Tuser();
				user.setUsername(CodeExchange.chinese(request
						.getParameter("username")));
				user.setPassword(CodeExchange.chinese(request
						.getParameter("password")));
				user.setUsertype(CodeExchange.chinese(request
						.getParameter("usertype")));
				// 这里还可以进一步校验 id 的合法性
				user.setId(Long.parseLong(request.getParameter("id")));
				UserDao userDao = new UserDao();
				// 这里还可以进一步查询用户名是否存在，避免用户名重复
				if (userDao.update(user)) {
					request.setAttribute("msg", "修改成功！");
				} else {
					request.setAttribute("msg", "修改失败！");
				}
			} else if (action.equals("login")) {
				Tuser user = new Tuser();
				user.setUsername(CodeExchange.chinese(request.getParameter("username")));
				user.setPassword(CodeExchange.chinese(request.getParameter("password")));
				UserDao userDao = new UserDao();
				ArrayList<Tuser> users = userDao.query(" username='"
						+ user.getUsername() + "' and password='"
						+ user.getPassword() + "'");
				if (users != null && users.size() > 0) {
					user = users.get(0);// 获取用户信息
					HttpSession session = request.getSession();
					// 用户登录信息存到 session
					session.setAttribute("loginusername", user.getUsername());
					session.setAttribute("loginusertype", user.getUsertype());
					// 添加Cookie
					Cookie cookie = new Cookie("SESSIONID", session.getId());// 创建一个键值对的cookie对象
					cookie.setMaxAge(60 * 60 * 24 * 7);// 设置cookie的生命周期
					response.addCookie(cookie);// 添加到response中
					// 转向修改页面编辑信息
					request.getRequestDispatcher("index.jsp").forward(request, response);
					return;
				} else {
					request.setAttribute("msg", "登录失败！");
					request.getRequestDispatcher("login.jsp").forward(request, response);
					return;
				}
			} else if (action.equals("logout")) {
				HttpSession session = request.getSession();
				session.removeAttribute("loginusername");
				session.removeAttribute("loginusertype");
				// 获取Cookies数组
			    Cookie[] cookies = request.getCookies();
			    // 迭代查找并清除Cookie
			    for (Cookie cookie: cookies) {
			        if (cookie.getName().equals("SESSIONID")) {
			            cookie.setMaxAge(0);
			            response.addCookie(cookie);
			        }
			    }
			    request.setAttribute("msg", "您已成功退出登录！");
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return;
			} else {
				// 不能识别动作
				response.sendRedirect("error.jsp");// 设计一个错误页面来显示
				return;
			}
		}
		// 查询条件
		String whereSQL = "";
		String keyword = CodeExchange.chinese(request.getParameter("keyword"));
		String keyword_group = CodeExchange.chinese(request
				.getParameter("keyword-group"));
		String fieldname = CodeExchange.chinese(request
				.getParameter("fieldname"));
		if ((keyword.equals("") || keyword == null)
				&& fieldname.equals("usertype")) {
			keyword = keyword_group;
		}
		if (keyword != null && fieldname != null && fieldname.length() > 0
				&& keyword.length() > 0) {
			// id 为整型
			if (fieldname.equals("id")) {
				whereSQL = fieldname + "=" + keyword;
			}
			// 其他为字符串型，要加入单引号
			else {
				whereSQL = fieldname + " like '%" + keyword + "%' ";
			}
			// 回传给页面显示查询条件，否则会清空
			request.setAttribute("fieldname", fieldname);
			request.setAttribute("keyword", keyword);
		}
		// 查询页码
		String page = request.getParameter("page");
		if (page == null) {
			page = "1";
		}
		UserDao userDao = new UserDao();
		ArrayList<Tuser> users = new ArrayList<Tuser>();
		users = userDao.queryPage(whereSQL, Integer.parseInt(page));
		request.setAttribute("users", users);
		int total = userDao.count(whereSQL);
		request.setAttribute("total", total / userDao.PAGE_LENGTH + 1);// 计算总页数
		request.setAttribute("currentPage", Integer.parseInt(page));
		request.getRequestDispatcher("userlist.jsp").forward(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
